﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Net_SCADA;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using WZXC_GBL_QUERY;

namespace NetSCADA_QUERY
{
    public partial class Form_QueryAlarmByDay : Form
    {
        

        private Size ScreenSize;
        bool isLoadInterface;
        DateTime queryStarttime;
        DateTime queryEndtime;
        bool isQueryByDay;
        string BatchSerial;

        #region 打印输出到打印机 变量
        PrintDocument print = new PrintDocument();
        string DefaultPrinterName = "";
        int totalpages = 0;
        int CurrentPageIndex = 0;
        float pageMargin = 30f;
        float MarginScale = 0.0336134f;
        SizeF pageSize = new SizeF(100, 100);
        string[] his_AlarmTitle = new string[5] { "序号", "警报名称", "等级", "发生时间", "复位时间" };
        float[] gridwidth = new float[5] { 50f, 255f, 50f, 100f, 100f };
        float[] gridscale = new float[5] { 0.09f, 0.46f, 0.09f, 0.18f, 0.18f };

        #endregion 

        public Form_QueryAlarmByDay(bool queryByDay, string batchserial, DateTime dtStart,DateTime dtEnd)
        {
            InitializeComponent();
            queryStarttime = dtStart;
            queryEndtime = dtEnd;
            isQueryByDay = queryByDay;
            BatchSerial = batchserial;
        }

        private void Form_QueryAlarmByDay_Load(object sender , EventArgs e)
        {
            isLoadInterface = true;
            ScreenSize = Screen.PrimaryScreen.Bounds.Size;
            print.PrintPage += Print_PrintPage;
            print.QueryPageSettings += Print_QueryPageSettings;
            DefaultPrinterName  = PubPrint.LoadPrinters(print, cmb_Printers);
            Show();
            setInterface();
            isLoadInterface = false;
            showAlarm(queryStarttime,queryEndtime);
        }

        private void Print_QueryPageSettings(object sender, QueryPageSettingsEventArgs e)
        {
            e.PageSettings.Landscape = false;//控制打印方向，flase 纵向
        }

        private void setInterface()
        {
            dtp_Day.Value = queryStarttime.Date;
            dtp_Day.Visible = isQueryByDay;
           // btn_PrintAlarm.Location = new Point(ScreenSize.Width - btn_PrintAlarm.Width - 5 , ScreenSize.Height - btn_PrintAlarm.Height -25);
            dtp_Day.Location = new Point(ScreenSize.Width - dtp_Day.Width - 5 , 1);
            //pnl_AlarmQuery.Size = new Size(ScreenSize.Width, ScreenSize.Height - lbl_ProductTitle.Height - btn_PrintAlarm.Height -28);
            pnl_Print.Location = new Point(ScreenSize.Width/2-pnl_Print.Width /2, ScreenSize.Height/2-pnl_Print.Height /2);
        }

        private void LoadAlarmInterface()
        {
            lst_Alarm.Clear();
            lst_Alarm.Location = new Point(2 , 30);
            lst_Alarm.Size = new Size(pnl_AlarmQuery.Width - 4 , pnl_AlarmQuery.Height - 40);
            lst_Alarm.Columns.Add(his_AlarmTitle[0] , 100 , HorizontalAlignment.Left);
            lst_Alarm.Columns.Add(his_AlarmTitle[1] , lst_Alarm.Width - 622 , HorizontalAlignment.Center);
            lst_Alarm.Columns.Add(his_AlarmTitle[2] , 100 , HorizontalAlignment.Left);
            lst_Alarm.Columns.Add(his_AlarmTitle[3] , 200 , HorizontalAlignment.Left);
            lst_Alarm.Columns.Add(his_AlarmTitle[4] , 200 , HorizontalAlignment.Left);
        }

        
        private void showAlarm(DateTime startDatetime,DateTime endDatetime)
        {
            LoadAlarmInterface();
            DataTable dt = DBOperate.GetAlarmHistory(startDatetime, endDatetime);

            if (dt == null || dt.Rows.Count == 0)
            {
                if(isQueryByDay) 
                    lbl_AlarmQueryTitle.Text = startDatetime.ToString("yyyy年MM月dd日") + " 没有警报记录";
                else
                    lbl_AlarmQueryTitle.Text ="批次：" + BatchSerial + " 没有警报记录";
                btn_DefaultPrint.Enabled = btn_Print.Enabled = false;
                return;
            }
            btn_DefaultPrint.Enabled = btn_Print.Enabled = true;
            if(isQueryByDay) 
                lbl_AlarmQueryTitle.Text = startDatetime.ToString("yyyy年MM月dd日") + " 警报记录";
            else
                lbl_AlarmQueryTitle.Text = "批次：" + BatchSerial + " 警报记录";
            for (int i = dt.Rows.Count - 1 ; i >= 0 ; i--)
            {
                if (dt.Rows[i]["AlarmActive"].ToString() == "0")
                {
                    lst_Alarm.Items.Add(new ListViewItem(new string[] { (lst_Alarm.Items.Count + 1).ToString() , dt.Rows[i]["AlarmName"].ToString() , dt.Rows[i]["AlarmLevel"].ToString() , "" , dt.Rows[i]["SaveTime"].ToString() }));//最后是报警等级，最后修改
                }
                else
                {
                    //1这里加载数据，对数据进行重组
                    int lastindex = -10;
                    for (int k = lst_Alarm.Items.Count - 1 ; k >= 0 ; k--)
                    {
                        if (dt.Rows[i]["AlarmName"].ToString() == lst_Alarm.Items[k].SubItems[1].Text && lst_Alarm.Items[k].SubItems[3].Text == "")
                        {
                            lst_Alarm.Items[k].SubItems[3].Text = dt.Rows[i]["SaveTime"].ToString();
                            lastindex = k;
                            break;
                        }
                    }
                    if (lastindex == -10)
                    {
                        lst_Alarm.Items.Add(new ListViewItem(new string[] { (lst_Alarm.Items.Count + 1).ToString() , dt.Rows[i]["AlarmName"].ToString() , dt.Rows[i]["AlarmLevel"].ToString() , dt.Rows[i]["SaveTime"].ToString() , "" }));
                    }
                }
            }
        }

        private void dtp_Day_ValueChanged(object sender , EventArgs e)
        {
            if (isLoadInterface) return;
            queryStarttime = dtp_Day.Value;
            queryEndtime = dtp_Day.Value.AddDays(1);
            showAlarm(queryStarttime,queryEndtime);
        }



        #region 打印到打印机



        private void PrintAlarm()
        {
            CurrentPageIndex = 0;
            totalpages = (lst_Alarm.Items.Count - 1) / 40;
            pageSize = new SizeF(print.PrinterSettings.DefaultPageSettings.PrintableArea.Width, print.PrinterSettings.DefaultPageSettings.PrintableArea.Height);
            pageMargin = print.PrinterSettings.DefaultPageSettings.PrintableArea.Width * MarginScale;
            for (int i = 0; i < gridwidth.Length; i++)
            {
                gridwidth[i] = (pageSize.Width - pageMargin * 2) * gridscale[i];
            }
            print.Print();
            pnl_Print.Visible = false;
        }

        private void Print_PrintPage(object sender, PrintPageEventArgs e)
        {
            e.HasMorePages = CurrentPageIndex<totalpages;
            //try
            {
                if (isQueryByDay)
                    PrintTitle(e.Graphics, QueryForms.fmquery.netline.LineName + " - " + dtp_Day.Value.ToString("yyyy年MM月dd日 ") + " 警报信息", 1);//想办法居中
                else
                    PrintTitle(e.Graphics , "批次：" + BatchSerial + " 警报信息", 1);//想办法居中hics.DrawString(s, fntTxt, brush, 10f, 10f); // print.DefaultPageSettings.PaperSize.Width / 2 - e.Graphics.MeasureString(s, fntTxt).Width / 2, 58f);//打印内容
                PrintGrid(e.Graphics, CurrentPageIndex < totalpages ? 40 : lst_Alarm.Items.Count - totalpages * 40);
                PrintDate(e.Graphics, lst_Alarm.Items.Count-CurrentPageIndex * 40-1, CurrentPageIndex < totalpages ? lst_Alarm.Items.Count-(CurrentPageIndex + 1) * 40-1 : -1);
                PrintTail(e.Graphics , CurrentPageIndex + 1 , totalpages + 1);
            }

            //catch
            //{
            //    MessageBox.Show(this, "打印出错！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //}
                CurrentPageIndex++;
        }



        private void PrintAlarmToPDF()
        {            //从表格中获取数据并打印成PDF，打开PDF文件
            string pdfFilename=Application.StartupPath + "\\RecordData\\AlarmPDF\\";
            if (!Directory.Exists(pdfFilename)) Directory.CreateDirectory(pdfFilename);
            pdfFilename+=   "Alarm " + dtp_Day.Value.ToString("yyyy-MM-dd")+".pdf";
            fd_PDF pdf = new fd_PDF(PdfPageOrientation.Portrait);
            int totalpages=(lst_Alarm.Items.Count-1)/40;
            for (int i = 0 ; i <= totalpages ; i++)
            {
                pdf.PagesAdd();
                if(isQueryByDay) 
                    PrintTitle(pdf , dtp_Day.Value.ToString("yyyy年MM月dd日 ") + " 警报信息" , 0);//想办法居中
                else
                    PrintTitle(pdf , "批次：" + BatchSerial + " 警报信息" , 0);//想办法居中
                PrintLog(pdf);
                PrintGrid(pdf ,i< totalpages? 40: lst_Alarm.Items.Count- totalpages *40);
                PrintDate(pdf , i * 40 , i < totalpages ? (i + 1) * 40 : lst_Alarm.Items.Count);
                PrintTail(pdf , i + 1 , totalpages + 1);
            }
            pdf.SaveToPDF(pdfFilename);
            foreach (PdfPageBase page in pdf.Doc.Pages)
            {
                pdf.PageRemove(page);
            }
            pdf.Doc = null;
            System.Diagnostics.Process.Start(pdfFilename);
        }
        private void PrintDate(Graphics g, int fromindex, int toindex)
        {
            Font ft = new Font("宋体", 12f, FontStyle.Regular);
            Brush brush = new SolidBrush(Color.Black);//画刷  
            float h = (pageSize.Height  - pageMargin * 4) / 41;
            float hinterval = (h - g.MeasureString("报警", ft).Height) / 1;
            for (int j = fromindex; j > toindex; j--)
            {
                float l = pageMargin;
                for (int i = 0; i < 5; i++)
                {
                    if (i > 2 && DateTime.TryParse(lst_Alarm.Items[j].SubItems[i].Text, out DateTime dt))
                        g.DrawString(dt.ToString("HH:mm:ss"), ft, brush, new PointF(l + 2, pageMargin * 3 + ( fromindex-j + 1) * h + hinterval));
                    else if(i==0)
                        g.DrawString((lst_Alarm.Items.Count- Convert.ToInt32(lst_Alarm.Items[j].SubItems[0].Text)+1).ToString(), ft, brush, new PointF(l + 2, pageMargin * 3 + (fromindex-j + 1) * h + hinterval));
                    else
                        g.DrawString(lst_Alarm.Items[j].SubItems[i].Text, ft, brush, new PointF(l + 2, pageMargin * 3 + (fromindex-j + 1) * h + hinterval));
                    l += gridwidth[i];
                }
            }
        }
        private void PrintDate(fd_PDF pdf , int fromindex ,int toindex)
        {
            PdfTrueTypeFont fontTitle = new PdfTrueTypeFont(new Font("宋体", 12f, FontStyle.Regular), true);
            PdfSolidBrush brush = pdf.BrushColor(Color.Black);
            float h=(pdf.PageHeight-pdf.Margin *2-40)/41;
            for (int j = fromindex ; j < toindex ; j++)
            {
                float l=pdf.Margin;
                for (int i = 0 ; i < 5 ; i++)
                {
                    if(i>2 && DateTime.TryParse(lst_Alarm.Items[j].SubItems[i].Text,out DateTime dt))
                        pdf.DrawString(dt.ToString("HH:mm:ss") , fontTitle , brush , new PointF(l + 2 , pdf.Margin + 42 + (j - fromindex + 1) * h));
                    else
                        pdf.DrawString(lst_Alarm.Items[j].SubItems[i].Text , fontTitle , brush , new PointF(l + 2 , pdf.Margin + 42+(j-fromindex+1)*h));
                    l += gridwidth[i];
                }
            }
        }

        private void PrintGrid(Graphics g, int lines)
        {
            Pen pen = new Pen(Color.Black,1f); //线条颜色
            Brush brush = new SolidBrush(Color.Black);//画刷  
            Font ft = new Font("宋体", 12f, FontStyle.Regular);
            float h = (pageSize.Height  - pageMargin * 4) / 41;
            float l = pageMargin;
            float hinterval = (h - g.MeasureString("报警", ft).Height) / 1;
            for (int i = 0; i < 5; i++)
            {
                g.DrawLine(pen, new PointF(l, pageMargin *3), new PointF(l, pageMargin *3 + h * (lines + 1)));
                g.DrawString(his_AlarmTitle[i], ft, brush, new PointF(l + 2, pageMargin *3+ hinterval));
                l += gridwidth[i];
            }
            g.DrawLine(pen, new PointF(pageSize.Width  - pageMargin, pageMargin*3), new PointF(pageSize.Width  - pageMargin, pageMargin *3 + h * (lines + 1)));

            for (int i = 0; i <= lines + 1; i++)
            {
                g.DrawLine(pen, new PointF(pageMargin, pageMargin*3+ i * h), new PointF(pageSize.Width  - pageMargin, pageMargin *3 + i * h));
            }
        }
        private void PrintGrid(fd_PDF pdf,int lines)
        {
            PdfPen pen=pdf.PenColor(Color.Black,1f);
            PdfSolidBrush brush = pdf.BrushColor(Color.Black);
            PdfTrueTypeFont fontTitle = new PdfTrueTypeFont(new Font("宋体", 12f, FontStyle.Regular), true);
            float h=(pdf.PageHeight-pdf.Margin *2-40)/41;
            float l=pdf.Margin;
            for (int i = 0 ; i < 5 ; i++)
            {
                pdf.DrawLine(pen , new PointF(l , pdf.Margin + 40) , new PointF(l, pdf.Margin + 40+h*(lines+1)));
                pdf.DrawString(his_AlarmTitle[i] , fontTitle , brush , new PointF(l+2 , pdf.Margin + 42));
                l += gridwidth[i];
            }
            pdf.DrawLine(pen , new PointF(pdf.PageWidth - pdf.Margin , pdf.Margin + 40) , new PointF(pdf.PageWidth - pdf.Margin , pdf.Margin + 40 + h * (lines + 1)));

            for (int i = 0 ; i <= lines+1 ; i++)
            {
                pdf.DrawLine(pen , new PointF(pdf.Margin , pdf.Margin + 40+i*h) , new PointF(pdf.PageWidth- pdf.Margin  , pdf.Margin + 40 + i * h));
            }
        }

        private void PrintLog(fd_PDF pdf)
        {
            //打印LOG
            string logfile=Application.StartupPath + @"\log.bmp";
            if (!File.Exists(logfile)) return;
            Image img = Image.FromFile(logfile);
            pdf.DrawImage(img , new RectangleF(pdf.PageWidth - img.Width - pdf.Margin , -10 + pdf.Margin , img.Width  , img.Height ));
        }
        private  void PrintTitle(Graphics g , string title , int lcr)
        {
            Font ft = new Font("微软雅黑", 16f, FontStyle.Regular);
            Brush brush = new SolidBrush(Color.Black);//画刷  
            float w = g.MeasureString(title, ft).Width; //  g.GetTextSize(ft, title).Width;
            float left = pageMargin;
            if (lcr == 1) left = (pageSize.Width  - w) / 2;
            if (lcr == 2) left = pageSize.Width - w;
            g.DrawString(title, ft, brush, new PointF(left, pageMargin));
        }
        private  void PrintTitle(fd_PDF pdf , string title , int lcr)
        {
            Font ft=new Font("微软雅黑", 16f, FontStyle.Regular);
            PdfTrueTypeFont fontTitle = new PdfTrueTypeFont(ft, true);
            PdfSolidBrush brush = pdf.BrushColor(Color.Black);
            float w=pdf.GetTextSize(ft,title).Width ;
            float left=pdf.Margin;
            if (lcr == 1) left = (pdf.PageWidth - w) / 2;
            if (lcr == 2) left = pdf.PageWidth - w;
            pdf.DrawString(title , fontTitle , brush , new PointF(left , pdf.Margin));
        }
        private void PrintTail(Graphics g, int index, int total)
        {
            Font ft = new Font("宋体", 9f, FontStyle.Regular);
            Brush brush = new SolidBrush(Color.Black);//画刷  
            StringBuilder sb = new StringBuilder().Append("第").Append(index).Append("页 共").Append(total).Append("页");
            float w = g.MeasureString(sb.ToString(),ft).Width;
            float left = pageSize.Width  - pageMargin - w;
            g.DrawString(sb.ToString(), ft, brush, new PointF(left, pageSize.Height  - pageMargin*0.9f));
        }

        private void PrintTail(fd_PDF pdf , int index,int total )
        {
            Font ft=new Font("宋体", 9f, FontStyle.Regular);
            PdfTrueTypeFont fontTitle = new PdfTrueTypeFont(ft, true);
            PdfSolidBrush brush = pdf.BrushColor(Color.Black);
            StringBuilder sb=new StringBuilder().Append("第").Append(index).Append("页 共").Append(total).Append("页");
            float w=pdf.GetTextSize(ft,sb.ToString()).Width ;
            float left=pdf.PageWidth-pdf.Margin-w;
            pdf.DrawString(sb.ToString() , fontTitle , brush , new PointF(left ,pdf.PageHeight-pdf.Margin+2f));
        }
        private void btn_Print_Click(object sender, EventArgs e)
        {
            pnl_Print.Visible = true;
           // PrintAlarmToPDF();
        }
        private void btn_DefaultPrint_Click(object sender, EventArgs e)
        {
            if (DefaultPrinterName !="")
                PrintAlarm();
            else
                MessageBox.Show("默认打印机没有设置好，请先设置默认打印机。");
        }

        private void btn_PrintConfirm_Click(object sender, EventArgs e)
        {
            if (DefaultPrinterName == "") return;
            if (DefaultPrinterName != cmb_Printers.Text) //保存为默认打印机
            { 
                DefaultPrinterName = cmb_Printers.Text; 
                PubPrint.SaveDefaultPrinter(DefaultPrinterName); 
            }
            print.PrinterSettings.PrinterName = DefaultPrinterName;

            PrintAlarm();
        }
        private void btn_Close_Click(object sender, EventArgs e)
        {
            pnl_Print.Visible = false;
        }

        #endregion
    }
}


